package net.qqxh.service.impl;

import com.google.gson.Gson;
import net.qqxh.common.utils.FileAnalysisTool;
import net.qqxh.persistent.Jfile;
import net.qqxh.persistent.SearchLib;
import net.qqxh.service.FileEsService;
import net.qqxh.service.task.FileResolveTask;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("fileEsService")
public class FileEsServiceImpl implements FileEsService {
    private final static Logger logger = LoggerFactory.getLogger(FileResolveTask.class);
    private static String ES_TYPE = "content";
    @Autowired
    private TransportClient esclient;

    @Override
    public boolean createFileIndex(SearchLib searchLib) throws IOException {
        CreateIndexRequestBuilder cib = esclient.admin().indices().prepareCreate(searchLib.getEsIndex());
        XContentBuilder mapping = null;
        switch (searchLib.getAnalysisMode()) {
            case "ik":
                mapping = XContentFactory.jsonBuilder()
                        .startObject()
                        //设置之定义字段
                        .startObject("properties")
                        .startObject("name")
                        .field("type", "text").field("analyzer", "ik_max_word").field("search_analyzer", "ik_smart")
                        .endObject()
                        //设置数据类型
                        .startObject("path")
                        .field("type", "text")
                        .endObject()
                        .startObject("content")
                        .field("type", "text").field("analyzer", "ik_max_word").field("search_analyzer", "ik_smart")
                        .endObject()
                        .startObject("viewFix")
                        .field("type", "text")
                        .endObject()
                        .endObject()
                        .endObject();
                break;
            default:
                mapping = XContentFactory.jsonBuilder()
                        .startObject()
                        //设置之定义字段
                        .startObject("properties")
                        .startObject("name")
                        .field("type", "text")
                        .endObject()
                        //设置数据类型
                        .startObject("path")
                        .field("type", "text")
                        .endObject()
                        .startObject("content")
                        .field("type", "text")
                        .endObject()
                        .startObject("viewFix")
                        .field("type", "text")
                        .endObject()
                        .endObject()
                        .endObject();
                break;
        }

        cib.addMapping(ES_TYPE, mapping);
        CreateIndexResponse res = cib.execute().actionGet();
        logger.info("----------添加映射成功----------");
        return true;
    }

    @Override
    public String addFile2ES(String esIndex, String content, String name, String path, String viewFix) throws IOException {
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", name)
                .field("path", path)
                .field("content", content)
                .field("viewFix", viewFix)
                .endObject();
        IndexResponse response = esclient.prepareIndex(esIndex, ES_TYPE).setSource(xContentBuilder).get();
        String id = response.getId();
        return id;
    }

    @Override
    public String deleteFileFromEs(String esIndex, String rid) {
        DeleteResponse deleteResponse = esclient.prepareDelete(esIndex, ES_TYPE, rid).execute().actionGet();
        return deleteResponse.getId();
    }

    @Override
    public List<Jfile> findFileByPath(SearchLib searchLib, String path) {
        List<Jfile> list = new ArrayList<Jfile>();
        QueryBuilder matchQuery = QueryBuilders.matchPhraseQuery("path", path);
        SearchResponse response = esclient.prepareSearch(searchLib.getEsIndex())
                .setQuery(matchQuery)
                .execute().actionGet();
        SearchHits searchHits = response.getHits();
        for (SearchHit searchHit : searchHits.getHits()) {
            Map jfileMap = searchHit.getSourceAsMap();
            Jfile jfile = new Jfile();
            jfile.setRid(searchHit.getId());
            jfile.setViewFix(MapUtils.getString(jfileMap, "viewFix"));
            jfile.setPath(MapUtils.getString(jfileMap, "path"));
            String viewPath = FileAnalysisTool.getOffSiteViewDir(searchLib.getFileSourceDir(), searchLib.getFileViewDir(), MapUtils.getString(jfileMap, "path"), MapUtils.getString(jfileMap, "viewFix"));
            jfile.setName(MapUtils.getString(jfileMap, "name"));
            jfile.setViewPath(viewPath);
            list.add(jfile);
        }
        return list;
    }


    @Override
    public Jfile queryJfileByRid(SearchLib searchLib, String rid) {
        GetResponse response = esclient.prepareGet(searchLib.getEsIndex(), ES_TYPE, rid).execute().actionGet();
        Map jfileMap = response.getSourceAsMap();
        Jfile jfile = new Jfile();
        jfile.setRid(rid);
        jfile.setViewFix(MapUtils.getString(jfileMap, "viewFix"));
        jfile.setPath(MapUtils.getString(jfileMap, "path"));
        String viewPath = FileAnalysisTool.getOffSiteViewDir(searchLib.getFileSourceDir(), searchLib.getFileViewDir(), MapUtils.getString(jfileMap, "path"), MapUtils.getString(jfileMap, "viewFix"));
        jfile.setName(MapUtils.getString(jfileMap, "name"));
        jfile.setViewPath(viewPath);
        return jfile;
    }
}

